#ifndef LOGWORKER_HPP
#define LOGWORKER_HPP

#include <QObject>
#include <QFile>
#include <QTextStream>
#include <QMutex>
#include <QDateTime>
#include <QFileInfo>
#include <QtGlobal> // For QtMsgType
#include <QThread>

/**
 * @brief LogWorker 类在独立线程中处理日志写入操作
 */
class LogWorker : public QObject {
    Q_OBJECT
public:
    /**
     * @brief 构造函数，初始化日志文件
     * @param filePath 日志文件的路径
     * @param parent 父对象
     */
    explicit LogWorker(const QString &filePath, QObject *parent = nullptr)
        : QObject(parent), logFilePath(filePath), logFile(filePath), textStream(&logFile) {
        if (!logFile.open(QIODevice::Append | QIODevice::Text)) {
            // 无法打开日志文件，静默失败或根据需要处理错误
        }
    }

    /**
     * @brief 析构函数，关闭日志文件
     */
    ~LogWorker() {
        if (logFile.isOpen()) {
            logFile.close();
        }
    }

public slots:
    /**
     * @brief 处理日志消息并写入日志文件
     * @param type 日志类型
     * @param file 文件名
     * @param line 行号
     * @param function 函数名
     * @param msg 日志消息
     */
    void processLog(QtMsgType type, const QString &file, int line, const QString &function, const QString &msg) {
        if (!logFile.isOpen()) {
            return;
        }

        QString logLevel;
        switch (type) {
        case QtDebugMsg:
            logLevel = "DEBUG";
            break;
        case QtInfoMsg:
            logLevel = "INFO";
            break;
        case QtWarningMsg:
            logLevel = "WARNING";
            break;
        case QtCriticalMsg:
            logLevel = "CRITICAL";
            break;
        case QtFatalMsg:
            logLevel = "FATAL";
            break;
        default:
            logLevel = "UNKNOWN";
            break;
        }

        QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
        QString threadId = QString::number(reinterpret_cast<quintptr>(QThread::currentThreadId()));

        QString formattedMessage = QString("[%1] [%2] [%3:%4] [Thread %5] %6")
                                   .arg(timestamp, logLevel, file, QString::number(line), threadId, msg);

        {
            QMutexLocker locker(&mutex);
            textStream << formattedMessage << "\n";
            textStream.flush();
        }

        checkLogRotation();

        if (type == QtFatalMsg) {
            abort();
        }
    }

private:
    QString logFilePath;     /**< 日志文件的路径 */
    QFile logFile;           /**< 日志文件对象 */
    QTextStream textStream;  /**< 文本流对象 */
    QMutex mutex;            /**< 互斥锁，保护日志文件的写操作 */

    static const qint64 MAX_LOG_SIZE = 10 * 1024 * 1024; // 10 MB

    /**
     * @brief 检查并执行日志轮转
     */
    void checkLogRotation() {
        if(logFile.size() >= MAX_LOG_SIZE) {
            logFile.close();

            // 生成备份文件名
            QString backupFileName = QString("%1.%2").arg(logFilePath)
                                     .arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));

            // 重命名当前日志文件
            QFile::rename(logFilePath, backupFileName);

            // 重新打开日志文件
            logFile.open(QIODevice::Append | QIODevice::Text);
        }
    }
};

#endif // LOGWORKER_HPP
